/**
 * Copyright 2009-2010 - YangJiandong(chunquedong)
 * 
 * This file is part of ChunMap project
 * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE(Version >=3)
 * 你可以自由复制、传播本项目的下载包文件，但必须保持其完整性。
 * 我们不用对使用中的风险及由此造成的损失承担任何责任。
 * 详细情况请见《ChunMap许可协议》。

 * 想了解更多有关ChunMap的信息，请访问http://code.google.com/p/chunmap/
 */
package chunmap.app.tools.navigate;

import java.awt.AWTEvent;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.MouseEvent;

import chunmap.app.bench.AbstractTool;
import chunmap.app.bench.EventType;
import chunmap.app.command.MoveToCommand;
import chunmap.view.View;
/**
 * @author chunquedong
 * 
 */
public class PanTool extends AbstractTool {

	private int x = 0;
	private int y = 0;
	private boolean draging = false;
	
	
	@Override
	public boolean actionEvent(AWTEvent event, EventType type) {

		if (event instanceof MouseEvent) {
			MouseEvent e = (MouseEvent) event;
			if (MouseEvent.MOUSE_PRESSED == e.getID()) {
				mousePressed(e);
			} else if (MouseEvent.MOUSE_RELEASED == e.getID()) {
				mouseReleased(e);
			} else if (MouseEvent.MOUSE_DRAGGED == e.getID()) {
				mouseDragged(e);
			}
		}
		
		return true;
	}

	public void mouseDragged(MouseEvent e) {
		if (!e.isMetaDown())
			return;
		int dx = e.getX() - x;
		int dy = e.getY() - y;

		Image image=map.getBufferImage();
		Graphics tg=image.getGraphics();
		((Graphics2D) tg).setBackground(Color.white);
		
		tg.clearRect(0, 0, image.getWidth(null),image.getHeight(null));
		tg.drawImage(map.getOriginImage(), dx, dy,null);
		image.flush();
		map.getGraphics().drawImage(image, 0, 0,map);
	}

	public void mousePressed(MouseEvent e) {
		if (!e.isMetaDown())
			return;
		draging = true;
		x = e.getX();
		y = e.getY();
	}

	public void mouseReleased(MouseEvent e) {
		if (draging) {

			View view=map.getView();
			
			int dx = e.getX() - x;
			int dy = e.getY() - y;
			
			double w = view.getWidth() / 2d - dx;
            double h = view.getHeight() / 2d - dy;

            double xx = view.x2World(w);
            double yy = view.y2World(h);

			MoveToCommand cmd = new MoveToCommand(map, xx, yy);
			map.executeCommand(cmd);

			draging = false;

			map.refreshMap();
		}
		x = 0;
		y = 0;
	}
}
